package cn.edu.ncu.housinghub.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private WebSocketAuthInterceptor webSocketAuthInterceptor;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置消息代理，用于推送消息给客户端
        config.enableSimpleBroker("/topic", "/queue");
        // 配置应用前缀，客户端发送消息的前缀
        config.setApplicationDestinationPrefixes("/housinghub");
        // 配置用户前缀，用于点对点消息
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册WebSocket端点，允许跨域，并添加身份验证拦截器
        registry.addEndpoint("/ws/chat")
                .setAllowedOrigins("http://localhost:5177", "http://localhost:5175", "http://localhost:5174", "http://localhost:5173", "http://localhost:3000", "http://127.0.0.1:5177")
                .addInterceptors(webSocketAuthInterceptor)
                .setHandshakeHandler(new WebSocketUserPrincipalHandshakeHandler())
                .withSockJS();
    }
}